import React, { useCallback, useEffect, useMemo, useState } from 'react';
import NavBar from '@/components/NavBar/NavBar';
import { Badge, Button, Dialog, InfiniteScroll, Popup, SearchBar, Stepper, Tag, Toast } from 'antd-mobile';
import Medicine from '@/views/ConsultType/ConsultMedicine/components/Medicine/Medicine';
import SubmitBar from '@/components/SubmitBar/SubmitBar';
import SvgIcon from '@/components/SvgIcon/SvgIcon';
import { useNavigate } from 'react-router-dom';
import { clearConsultInfo, createConsultOrder, fetchMedicineList, paymentConsultOrder, setMedicines } from '@/store/modules/consultStore';
import { useEnhanceDispatch, useEnhanceSelector } from '@/hooks';
import { Medical, MedicineList, MedicineParams, PaymentParams } from '@/type/ConsultType';
import lodash from 'lodash';
import './ConsultChoose.scss';

const ConsultChoose = () => {
  const navigate = useNavigate();
  const enhanceDispatch = useEnhanceDispatch();
  // 开药问诊的信息
  const consultInfo = useEnhanceSelector(state => state.consultStore.consultInfo);
  // 是否还有更多数据
  const [hasMore, setHasMore] = useState<boolean>(true);
  // 获取药品列表的参数
  const [medicineParams, setMedicineParams] = useState<MedicineParams>({ current: 1, pageSize: 10, keyword: '' });
  // 药品列表
  const [medicineList, setMedicineList] = useState<MedicineList>([]);
  // 选中的药品列表
  const [selectedMedicineList, setSelectedMedicineList] = useState<MedicineList>([]);
  // 选中的药品总价
  const totalPrice = useMemo(() => selectedMedicineList.reduce((pre, cur) => pre + Number(cur.amount) * Number(cur.quantity), 0), [selectedMedicineList]);
  // 药品列表总数
  const [total, setTotal] = useState<number>(0);
  //是否显示药品清单弹层
  const [visible, setVisible] = useState<boolean>(false);
  // 支付参数
  const [paymentConsultOrderParams, setPaymentConsultOrder] = useState<PaymentParams>({ paymentMethod: 1, payCallback: 'http://localhost:80/room', orderId: '' });
  const [loading, setLoading] = useState<boolean>(false);
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>选择药品</span>), []);

  /**
   * @description 获取药品列表的回调函数
   * */
  const fetchMedicine = async (medicineParams: MedicineParams) => {
    try {
      const { rows, total } = await enhanceDispatch(fetchMedicineList(medicineParams)).unwrap();
      setTotal(total);
      if (medicineParams.keyword.length) {
        setMedicineList(rows);
      } else {
        setMedicineList([...medicineList, ...rows]);
      }
      setMedicineParams({ ...medicineParams, current: medicineParams.current += 1 });
      if (medicineList.length >= total) {
        setHasMore(false);
      }
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  /**
   *搜索框输入值的回调函数
   * */
  const onChangeSearch = useCallback(lodash.throttle(async (keyword: string) => {
    const newMedicineParams = { ...medicineParams, current: 1, keyword };
    setMedicineParams(newMedicineParams);
    await fetchMedicine(newMedicineParams);
  }, 1000), []);

  /**
   * @description 子组件调用的回调函数
   * */
  const changeQuantity = (id: string, quantity: number) => {
    const find = medicineList?.find((item) => item.id === id) as Medical;
    find.quantity = quantity + '';
    setMedicineList([...medicineList]);
  };

  const onMasskClick = () => {
    setVisible(false);
  };

  /**
   * @description 点击提交订单按的回调函数
   * */
  const handleSubmit = async () => {
    if (!selectedMedicineList.length) {
      Toast.show('请选择药品');
      return;
    }
    try {
      setLoading(true);
      const { id: orderId } = await enhanceDispatch(createConsultOrder(consultInfo)).unwrap();
      setVisible(true);
      setPaymentConsultOrder({ ...paymentConsultOrderParams, orderId });
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    } finally {
      setLoading(false);
    }
  };

  /**
   * @description 清空药品清单的回调函数
   * */
  const clear = async () => {
    const confirm = await Dialog.confirm({ content: '确定清空选择的药品吗?', header: '温馨提示' });
    if (!confirm) return;
    medicineList.forEach(item => item.quantity = '0');
    setSelectedMedicineList([]);
    setMedicineList([...medicineList]);
    setVisible(false);
  };


  /**
   * @description 申请开方的回调函数
   * */
  const handleExtraction = async () => {
    navigate(`/room?orderId=${paymentConsultOrderParams.orderId}&from=medicine`);
    enhanceDispatch(clearConsultInfo());
  };

  useEffect(() => {
    const selectedMedicineList = medicineList.filter(item => Number(item.quantity) > 0);
    setSelectedMedicineList(selectedMedicineList);
    enhanceDispatch(setMedicines(selectedMedicineList.map((item) => ({ id: item.id, quantity: Number(item.quantity) }))));
  }, [medicineList]);

  const renderPrice = () => {
    return (
      <>
        <Badge content={selectedMedicineList.length}>
          <div className="restoratives">
            <SvgIcon name="restoratives" width="25px" height="25px"></SvgIcon>
          </div>
        </Badge>
        <span className="price">￥{totalPrice.toFixed(2)}</span>
      </>
    );
  };

  return (
    <div className="consult-choose">
      {/*导航栏组件*/}
      <NavBar back={left()} children={children()} onBack={() => navigate(-1)}></NavBar>
      {/*搜索组件*/}
      <SearchBar placeholder="请输入药品名称" showCancelButton value={medicineParams.keyword} onChange={onChangeSearch}></SearchBar>
      {/*药品列表*/}
      <div className="medicine-list">
        {medicineList?.map((item) => (<Medicine medical={item} key={item.id} changeQuantity={changeQuantity}></Medicine>))}
        <InfiniteScroll loadMore={() => fetchMedicine(medicineParams)} hasMore={hasMore} />
      </div>
      <SubmitBar left={renderPrice()} right={<Button color="primary" onClick={handleSubmit} loading={loading}>提交订单</Button>}></SubmitBar>

      {/*药品清单*/}
      <Popup visible={visible} bodyStyle={{ borderTopLeftRadius: '8px', borderTopRightRadius: '8px', height: '60vh' }} onMaskClick={onMasskClick}>
        <div className="header">
          <div className="left">
            <span className="drug">药品清单</span>
            <span className="count">(共{selectedMedicineList.length}件商品,合计:{totalPrice}元)</span>
          </div>
          <div className="right">
            <SvgIcon name="clear" width="15px" height="15px"></SvgIcon>
            <span className="clear" onClick={clear}>清空</span>
          </div>
        </div>
        <div className="medicine-list">
          {selectedMedicineList?.map((item) => (<Medicine medical={item} key={item.id} changeQuantity={changeQuantity}></Medicine>))}
        </div>
        <SubmitBar left={renderPrice()} right={<Button loading={loading} color="primary" onClick={handleExtraction}>申请开方</Button>}></SubmitBar>
      </Popup>
    </div>
  );
};

export default ConsultChoose;